package cn.tangshh.universal.core.config;

import cn.tangshh.universal.core.util.RegexUtil;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.context.MessageSourceProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 国际化配置类
 *
 * @author Tang
 * @version v1.0
 * @since 2024/05/30
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class I18nMessageConfig {
    private final MessageSourceProperties properties;
    private final ResourceBundleMessageSource messageSource;

    /**
     * 新增实例化后操作
     */
    @PostConstruct
    public void afterPropertiesSet() {
        String path = properties.getBasename();
        if (RegexUtil.verify(path, "^\\w*([./](\\*|\\w*))+$")) {
            try {
                // 以下写法是为了跨模块打包时也能加载到，如文件定义在core模块下在server模块打jar包，一样可以正常使用
                PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                Resource[] resources = resolver.getResources(ResourceLoader.CLASSPATH_URL_PREFIX + path.replace(".", "/"));
                List<String> baseNames = new ArrayList<>();
                for (Resource resource : resources) {
                    String filename = resource.getFilename();
                    if (filename != null && filename.matches("[\\w-_]*(?![a-zA-z]{2}_[a-zA-Z]{2})\\.properties")) {
                        baseNames.add(path.replace(".", "/").replace("*", resource.getFilename().split("\\.")[0]));
                    }
                }
                messageSource.setBasenames(baseNames.toArray(new String[]{}));
                messageSource.setDefaultEncoding("UTF-8");
                messageSource.setCacheSeconds(3000);
            } catch (IOException e) {
                log.error("i18n file path {} not found file/directory", path, e);
            }
        }
    }
}